package com.cloud.auth.biz.controller;

import com.cloud.auth.biz.jwt.user.UserCache;
import com.cloud.auth.biz.jwt.user.UserJwtClient;
import com.cloud.auth.biz.service.UserCacheService;
import com.cloud.common.result.R;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @author 王霄
 * @date 2022/2/23 11:10
 */
@RestController
@RequestMapping("/auth")
public class AuthController {

    private static final Map<String, String> USER_MOCK_DATA = new HashMap<>();

    static {
        USER_MOCK_DATA.put("wangxiao", "123456");
        USER_MOCK_DATA.put("admin", "123456");
    }

    @Resource
    private UserJwtClient jwtClient;
    @Resource
    private UserCacheService userCacheService;

    @PostMapping("/login")
    public R<String> login(String userId, String password) {
        if (!Objects.equals(password, USER_MOCK_DATA.get(userId))) {
            return R.fail("用户名或密码错误");
        }
        UserCache userCache = new UserCache(userId, "王霄", "wangxiao@qq.com");
        String token = jwtClient.generateToken(userId);
        userCacheService.saveUserCache(userCache);
        return R.ok(token);
    }

    @PostMapping("/refreshToken")
    public R<String> refreshToken(String oldToken) {
        if (jwtClient.verify(oldToken)) {
            return R.fail("token校验失败");
        }
        String userId = jwtClient.parseToken(oldToken);
        UserCache userCache = userCacheService.getUserCache(userId);
        if (userCache == null) {
            return R.fail("用户登录信息已失效");
        }
        userCacheService.delUserCache(userId);
        String newToken = jwtClient.generateToken(userId);
        userCacheService.saveUserCache(userCache);
        return R.ok(newToken);
    }
}
